import { MCPClient } from '../lib/mcp-sdk.js';
import winston from 'winston';

// 设置日志
const logger = winston.createLogger({
  level: 'info',
  format: winston.format.combine(
    winston.format.timestamp(),
    winston.format.json()
  ),
  transports: [
    new winston.transports.File({ filename: './logs/client.log' }),
    new winston.transports.Console()
  ]
});

class MCPDemoClient {
  constructor() {
    this.client = new MCPClient({
      serverUrl: 'http://localhost:3000'
    });
  }

  async connect() {
    try {
      await this.client.connect();
      logger.info('已连接到MCP服务器');
    } catch (error) {
      logger.error(`连接服务器失败: ${error.message}`);
      throw error;
    }
  }

  async processText(text, operation) {
    try {
      logger.info(`发送文本处理请求: ${operation}`);
      const result = await this.client.callTool('processText', { text, operation });
      logger.info(`文本处理结果:`, result);
      return result;
    } catch (error) {
      logger.error(`文本处理失败: ${error.message}`);
      throw error;
    }
  }

  async calculate(operation, numbers) {
    try {
      logger.info(`发送计算请求: ${operation}`);
      const result = await this.client.callTool('calculate', { operation, numbers });
      logger.info(`计算结果:`, result);
      return result;
    } catch (error) {
      logger.error(`计算失败: ${error.message}`);
      throw error;
    }
  }

  async readFile(path) {
    try {
      logger.info(`请求读取文件: ${path}`);
      const result = await this.client.getResource('file', path);
      logger.info(`文件读取成功`);
      return result;
    } catch (error) {
      logger.error(`文件读取失败: ${error.message}`);
      throw error;
    }
  }
}

export default MCPDemoClient;

// 示例使用
async function runExample() {
  const client = new MCPDemoClient();
  
  try {
    await client.connect();

    // 测试文本处理
    const text = "Hello, MCP!";
    console.log('\n1. 测试文本处理:');
    console.log('原始文本:', text);
    
    const wordCount = await client.processText(text, 'wordCount');
    console.log('单词数:', wordCount.count);
    
    const upperCase = await client.processText(text, 'toUpperCase');
    console.log('转换大写:', upperCase.text);

    // 测试缓存操作
    console.log('\n2. 测试缓存操作:');
    await client.cacheData('testKey', { message: 'Hello Cache' }, 'set');
    const cached = await client.cacheData('testKey', null, 'get');
    console.log('缓存的数据:', cached.value);

    // 测试文件读取
    console.log('\n3. 测试文件读取:');
    try {
      const fileContent = await client.readFile('./test.txt');
      console.log('文件内容:', fileContent.content);
    } catch (error) {
      console.log('文件读取失败 (预期的错误，因为文件不存在)');
    }

  } catch (error) {
    console.error('示例运行失败:', error);
  }
}

runExample(); 